package leetcode4;
import java.util.*;
class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
     }
}
public class Day11 {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        TreeNode t2 = new TreeNode(2);
        root.right = t2;
        TreeNode t3 = new TreeNode(3);
        t2.left = t3;
        postorderTraversal(root);
    }

    public static List<Integer> postorderTraversal(TreeNode root) {
        //左右根
        List<Integer> ret = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while(cur != null || !stack.isEmpty()) {
            //1.往左遍历
            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            //2.当前节点左边为空，如果右边不为为空则先记录当前节点，先去遍历右边的
            TreeNode peek = stack.peek();
            if(peek.right == null ) {
                ret.add(peek.val); //左右都为空，可以记录；或者左右都已经遍历完，可以记录根
                stack.pop();
            }else {
                cur = peek.right;
            }
        }
        return ret;
    }
}
